﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BallotCounter.Question;

namespace BallotCounter.Answer
{
    class Libby : IBallotCounter
    {
        public int BallotCount(int[] ballotArray)
        {
            if(ballotArray.Length==0)
            {
                return -1;
            }
            //Convert to a list and sort it.
            List<int> iList = ballotArray.ToList();
            iList.Sort();
            
            if(iList[0]<0)
            {
                return -1;
            }
            else if(iList.Count==1)
            {
                return iList[0];
            }

            int currentValue=iList[0];
            int currentCount=1;
            int currentMaxCount=0;
            int currentMaxValue = 0;
            int currentMaxAppearTimes = 0;
            for (int i = 1; i < iList.Count;i++ )
            {
                if (iList[i] == currentValue)
                {
                    currentCount++;
                }
                else
                {
                    if (currentCount > currentMaxCount)
                    {
                        currentMaxCount = currentCount;
                        currentMaxValue = currentValue;
                        currentMaxAppearTimes = 1;
                    }
                    else if(currentCount== currentMaxCount)
                    {
                        currentMaxAppearTimes++;
                    }
                    currentCount = 1;
                    currentValue=iList[i];
                }
            }            
            //When the max count is located at the last, for example {1,2,2,3,3,3}. For now, currentMaxCount would not be assigned currentCount'value, because i equals (iList.length-1) and 
            //only when two contiguous figures are different [currentMaxCount] would be re-assigned.
            if(currentCount>currentMaxCount)
            {
                return iList[iList.Count - 1];
            }

            if (currentMaxAppearTimes > 1)
            {
                return -1;
            }
            else if(currentMaxAppearTimes==1)
            {
                return currentMaxValue;
            }
            else
            {
                return currentValue;
            }
        }

    }
}
